﻿using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using YiShop.Framework.JwtBearer;

namespace YiShop.Framework.Utils
{
    public static class SecurityUtils
    {
        /// <summary>
        /// 获取请求token
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetToken(HttpRequest request)
        {
            if (request.Headers != null)
            {
                string? token = request.Headers["Authorization"];
                if (!string.IsNullOrEmpty(token) && token.StartsWith(GlobalConstants.TOKEN_PREFIX))
                {
                    token = token.Replace(GlobalConstants.TOKEN_PREFIX, "");
                    return token;
                }                
            }
            throw new ServiceException("获取用户信息异常", StatusCodes.Status401Unauthorized);
        }

        public static IEnumerable<Claim> ParseToken(string token)
        {
            var jwtSecurityToken = JWTEncryption.SecurityReadJwtToken(token);
            return jwtSecurityToken.Claims;
        }

        public static string GetUsername()
        {
            var userName = App.HttpContext?.User?.Identity?.Name;
            return userName ?? string.Empty;
        }

        public static long GetUserId()
        {
            var userId = App.HttpContext?.User.Claims.Where(c => c.Type.Equals(DataConstants.USER_ID)).FirstOrDefault()?.Value;
            if (long.TryParse(userId, out long id))
                return id;
            throw new ServiceException("获取ID失败");
        }

        #region 是否为管理员
        /// <summary>
        /// 是否为管理员
        /// </summary>
        /// <param name="userId">用户ID</param>
        public static bool IsAdmin(long? userId)
        {
            return userId != null && 1L == userId;
        }

        public static bool IsAdmin()
        {
            var userId = GetUserId();
            return IsAdmin(userId);
        }

        /// <summary>
        /// 是否为管理员角色
        /// </summary>
        /// <param name="roleId">角色ID</param>
        public static bool IsAdminRole(long? roleId)
        {
            return roleId != null && 1L == roleId;
        }
        #endregion

    }
}
